package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class SpuServiceImpl implements SpuService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private CateGoryBrandMapper cateGoryBrandMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;
    /**
     * 查询全部列表
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Spu findById(String id){
        return  spuMapper.selectByPrimaryKey(id);
    }


    /**
     * 增加
     * @param spu
     */
    @Override
    public void add(Spu spu){
        spuMapper.insert(spu);
    }


    /**
     * 修改
     * @param spu
     */
    @Override
    public void update(Spu spu){
        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id){
        spuMapper.deleteByPrimaryKey(id);
    }


    /**
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap){
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size){
        PageHelper.startPage(page,size);
        return (Page<Spu>)spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String,Object> searchMap, int page, int size){
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        return (Page<Spu>)spuMapper.selectByExample(example);
    }
    //保存商品 SPU+SKU列表
    @Transactional
    @Override
    public void addGoods(Goods goods) {
        Spu spu = goods.getSpu(); //拿到spu数据
        long l = idWorker.nextId(); //雪花算法生成ID
        spu.setId(l+"");    //把Id设置到Spu对象里
        spu.setIsDelete("0"); //逻辑删除
        spu.setIsMarketable("0"); //未上架
        spu.setStatus("0"); //审核状态
        spuMapper.insertSelective(spu); //把数据存到spu表中

        //保存sku集合数据到数据库
        saveSkuList(goods);
    }
    //根据spu_id查询商品
    @Override
    public Goods findBySpuId(String spuId) {
        Goods goods = new Goods();
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //构造查询对象
        Sku sku = new Sku();
        //设置查询条件
        sku.setSpuId(spuId);
        List<Sku> skuList = skuMapper.select(sku);
        goods.setSkuList(skuList);
        goods.setSpu(spu);
        return goods;
    }

    @Override
    public void updateGoods(Goods goods) {
        //1.根据spuId更新spu
        Spu spu = goods.getSpu();//拿到spu的数据
        spuMapper.updateByPrimaryKeySelective(spu); //把数据更新到spu表
        //2.根据spuId删除skuList
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",spu.getId());
        int i = skuMapper.deleteByExample(example);
        logger.info("删除skuList 大小：{}",i);
        //3.保存skuList
        saveSkuList(goods);
    }
    //商品审核
    @Override
    public void auditGoods(String spuId) {
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setStatus("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }
    //商品上架
    @Override
    public void upGoods(String spuId) {
        Spu spu1 = spuMapper.selectByPrimaryKey(spuId);
        if(spu1.getStatus().equals("0")){
            throw new RuntimeException("商品还未审核不能上架");
        }
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
        rabbitTemplate.convertAndSend("goods_up_exchange", "", spuId);
        logger.info("商品上架成功发送消息， spuId: {}", spuId);
        //
    }
    //商品下架
    @Override
    public void down(String spuId) {
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }
    //商品逻辑删除
    @Override
    public void deleteLogic(String spuId) {
        Spu spu1 = spuMapper.selectByPrimaryKey(spuId);
        if(spu1.getIsMarketable().equals("1")){
            throw new RuntimeException("商品正在上架，不能删除");
        }
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setIsDelete("1");
        spu.setStatus("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }
    //商品恢复
    @Override
    public void restore(String spuId) {
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setIsDelete("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }
    //商品物理删除
    @Override
    public void deleteGoods(String spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if(spu.getIsDelete().equals("0")){
            throw new RuntimeException("商品没有在回收站，请先逻辑删除后重试");
        }
        int i = spuMapper.deleteByPrimaryKey(spuId);
        logger.info("根据SpuId:{}删除，条数：{}",spuId,i);

    }
    /*
        tb_sku 表（SKU商品表）

        字段名称	字段含义	字段类型	字段长度	备注
        id	            商品id	VARCHAR
        sn	            商品条码	VARCHAR
        name	        SKU名称	VARCHAR
        price	        价格（分）	INT
        num	            库存数量	INT
        alert_num	    库存预警数量	INT
        image	        商品图片	VARCHAR
        images	        商品图片列表	VARCHAR
        weight	        重量（克）	INT
        create_time	    创建时间	DATETIME
        update_time	    更新时间	DATETIME
        spu_id	        SPUID	BIGINT
        category_id	    类目ID	INT
        category_name	类目名称	VARCHAR
        brand_name	    品牌名称	VARCHAR
        spec	        规格	VARCHAR
        sale_num	    销量	INT
        comment_num	    评论数	INT
        status	        商品状态 1-正常，2-下架，3-删除	CHAR
     */
    //保存skuList
    public void saveSkuList(Goods goods){
        //1.获取skuList
        List<Sku> skuList = goods.getSkuList();
        Spu spu = goods.getSpu(); //获取spu对象
        //2.遍历保存
        for (Sku sku : skuList) { //选择需要保存的字段 放循环里保存 id，name，price，num
            //2.1 id
            sku.setId(idWorker.nextId()+"");
            //2.2 name --->spu name + sku.spec "" --> {}
            //{'颜色': '梵高星空典藏版', '版本': '8GB+128GB'}
            String skuName = spu.getName();
            String specJson = sku.getSpec();
            //json字符串转map 此处为了防止下面json转换异常
            if(StringUtils.isEmpty(specJson)){
                specJson = "{}";
            }
            Map<String, String> specMap = JSON.parseObject(specJson, Map.class);
            Set<Map.Entry<String, String>> entries = specMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String value = entry.getValue();
                skuName = skuName+""+value;
            }
            //设置name
            sku.setName(skuName);
            //2.3 创建时间和更新时间
            sku.setCreateTime(new Date());
            sku.setUpdateTime(new Date());
            //2.4 spuId
            sku.setSpuId(spu.getId());
            //2.5 第三级分类id ————》来源于spu对象
            Integer category3Id = spu.getCategory3Id();
            sku.setCategoryId(category3Id);
            //2.6 分类名称----》根据分类id查询
            Category category = categoryMapper.selectByPrimaryKey(category3Id);
            if(category != null) {
                sku.setCategoryName(category.getName());
            }
            //2.7 品牌名称---》根据spu中的品牌id查询
            Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
            sku.setBrandName(brand.getName());
            //2.8维护品牌分类关联关系表
            CateGoryBrand cateGoryBrand = new CateGoryBrand();
            cateGoryBrand.setBrandId(brand.getId());
            cateGoryBrand.setCategoryId(spu.getCategory3Id());
            int i = cateGoryBrandMapper.selectCount(cateGoryBrand);
            if(i == 0){ //没有就新增
                cateGoryBrandMapper.insert(cateGoryBrand);
            }
            //保存
            skuMapper.insertSelective(sku);
        }

    }
    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andEqualTo("id",searchMap.get("id"));
           	}
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andEqualTo("sn",searchMap.get("sn"));
           	}
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
           	}
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
           	}
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
           	}
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
           	}
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
           	}
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
           	}
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
           	}
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
           	}
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andEqualTo("isMarketable",searchMap.get("isMarketable"));
           	}
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
           	}
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andEqualTo("isDelete",searchMap.get("isDelete"));
           	}
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andEqualTo("status",searchMap.get("status"));
           	}

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
